package priv.wangy.micro.common.sync.consumer;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import priv.wangy.micro.common.sync.DataSyncFactory;
import priv.wangy.micro.common.sync.constant.DataSyncObjectEnum;

import java.util.Objects;

/**
 * @author zhangjq
 * @since 2023-12-18
 */
@Slf4j
@Component
@Scope("prototype")
public class DataSyncConsumer implements IDataSyncConsumer {

    private final DataSyncFactory dataSyncFactory;

    public DataSyncConsumer(DataSyncFactory dataSyncFactory) {
        this.dataSyncFactory = dataSyncFactory;
    }

    @Override
    public void onMessage(Message message, Channel channel) {
        log.trace("接收到数据同步通知:{}", message.toString());
        System.out.println(message);
        String name = message.getMessageProperties().getReceivedExchange().split("\\.")[2];
        if (StringUtils.hasLength(name)) {
            DataSyncObjectEnum sync = DataSyncObjectEnum.getByName(name);
            if (Objects.nonNull(sync)) {
                dataSyncFactory.waitingSync(sync);
            }
        }
    }
}
